<template>
<div class="bg">
<div class="loginContent">
  <div class="title">智慧社区管理后台</div>
  <!-- 登录区域  -->
  <div v-show="islogin" class="login">
    <el-form ref="LoginForm"  :rules="Loginrules" :model="LoginForm" label-width="80px">
  <el-form-item  prop="userName">
    <span slot="label">
      <span style="color:white;font-size:18px">账号:</span>
    </span>
    <el-input v-model="LoginForm.userName"></el-input>
  </el-form-item>
 <el-form-item prop="passWord" >
    <span slot="label">
      <span style="color:white;font-size:18px">密码:</span>
    </span>
    <el-input v-model="LoginForm.passWord" type="password" @keyup.enter.native="loginToken('LoginForm')"></el-input>
  </el-form-item>
   <el-form-item>
      <el-checkbox v-model="checkpassword" style="color:white">记住密码</el-checkbox>
      <el-checkbox v-model="autologin" style="color:white">自动登录</el-checkbox>
   </el-form-item>
  <el-form-item>
   <el-button type="primary" @click="loginToken('LoginForm')">登录</el-button>
    <el-button @click="toRegister">注册</el-button>
  </el-form-item>
    </el-form>
  </div>
 <!-- 注册区域 -->
  <div v-show="!islogin" class="register">
    <el-form ref="RegisterForm" :rules="Registrules" :model="RegisterForm" label-width="80px">
  <el-form-item  prop="userName" >
    <span slot="label">
      <span style="color:white;font-size:18px">账号:</span>
    </span>
    <el-input v-model="RegisterForm.userName"></el-input>
  </el-form-item>
 <el-form-item prop="passWord" >
    <span slot="label">
      <span style="color:white;font-size:18px">密码:</span>
    </span>
    <el-input v-model="RegisterForm.passWord"></el-input>
  </el-form-item>
  <el-form-item>
   <el-button type="primary" @click="RegisterToken('RegisterForm')">确认注册</el-button>
    <el-button @click="toRegister">返回登录</el-button>
  </el-form-item>
    </el-form>
  </div>
</div>
</div>
</template>

<script>
import {mapState,mapMutations} from 'vuex'

export default {
  created() {
    document.title="登录"
    if (localStorage.getItem("checkpassword")) {
       let token = localStorage.getItem("loginToken")?this.$jwtCode(localStorage.getItem("loginToken")) :{userName:'', passWord:''}
       this.LoginForm.userName=token.userName
       this.LoginForm.passWord=token.passWord
       this.checkpassword=true
    }
    if (localStorage.getItem("autologin")) {
      if (localStorage.getItem("loginToken")) {
        this.$message.warning("3s后自动登录")
      setTimeout(()=>{
        if (this.autologin) {
          this.loginToken('LoginForm')
        }
      },3000)
      }
     
    
       this.autologin =true
    }
  },
  data() {
    var LoginUser = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入账号'));
        } else {
          if (value.length<5) {
            callback(new Error('账号长度不小于5位'));
          }
          callback();
        }
      };
    return {
      islogin:true,
      LoginForm:{
        userName:'',
        passWord:''
      },
      checkpassword:false,
      autologin:false,
      Loginrules:{
        userName:[
          { validator:LoginUser, trigger: 'blur' },
          
        ],
        passWord:[
          { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 10, message: '长度在 6 到 10个字符', trigger: 'blur' }
        ]
      },
       RegisterForm:{
        userName:'',
        passWord:''
      },
      Registrules:{
        userName:[
          { validator:LoginUser, trigger: 'blur' },
          
        ],
        passWord:[
          { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 10, message: '长度在 5 到 10个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations([
      'putUser'
    ]),
    toRegister(){
      this.islogin=!this.islogin
    },
    async waitLogin(){
      
    },
    loginToken(formName){
     
   this.$refs[formName].validate(async(valid) => {
          if (valid) {
            const {data: res} =await  this.$http.post('/users/login',this.LoginForm)
            console.log(res)
            if (res.status!=1) {
              this.$message.error('账号或者密码出错')
             return
            }
          const token =  res.token
          localStorage.setItem("loginToken",token)
         
          const result= this.$jwtCode(token)
          this.putUser(result)
       
           const userForm={name:this.user,password:this.password,time:this.time}
           const {data:res1}= await this.$http.post('/users/roles',userForm)
           console.log(res1)
           const {data:roleres} =await this.$http.get('/users/role/'+this.user)
           console.log(roleres)
           if (roleres.status==0) {
              this.$message.error("角色获取出错")
              return
           }

          this.$message.success('登录成功')
          if (roleres.result.role!="超级管理员") {
            this.$router.push('/user')
            return
          }
          this.$router.push('/home')

          } else {
            console.log('error submit!!');
            return false;
          }
        });
    this.$refs[formName].resetFields(); 
  },
   RegisterToken(formName){
this.$refs[formName].validate(async(valid)=>{
    if (valid) {
      const {data:res} =await this.$http.post('/users/register',this.RegisterForm)
      console.log(res)
      if (res.status==0) {
         this.$message.error('账号已经存在')
         return
      }
       this.$message.success('注册成功')
       this.islogin=true
        this.$refs[formName].resetFields(); 
    }
})
  }
 

  },
  watch:{
    checkpassword(nvalue,ovalue){
      if (ovalue) {
        localStorage.removeItem("checkpassword")
      }
      if (nvalue) {
        localStorage.setItem("checkpassword",nvalue)
      }
    },
     autologin(nvalue,ovalue){
      if (ovalue) {
        localStorage.removeItem("autologin")
      }
      if (nvalue) {
        if (!localStorage.getItem("checkpassword")) {
          this.$message.warning("请先记住密码")
          return
        }
       localStorage.setItem("autologin",nvalue)
      }
    }
  },
  computed:{
    ...mapState([
      'user',
      'password',
      'time'
    ])
  }
 
 
}
</script>

<style scoped>
.bg{
  width: 100vw;
  height: 100vh;
 background-image: url(../../public/image/bg.jpg);
 background-size: cover;
 display: flex;
 align-items: center;
 justify-content: center;
}
.loginContent{
  width: 30rem;
  height: 30rem;
 background-image: url(../../public/image/bg2.png);
 background-size: 25rem;
 background-repeat: no-repeat;
 background-position: 60% 50%;
  border-radius: 2rem;
  position: relative;
}
.title{
  left: 20%;
  top: 5%;
  position: absolute;
  color: white;
  font-size: 35px;
}
.login{
  width: 20rem;
  height: 20rem;
  position: absolute;
  left: 0;
  top: 50%;
  border-radius: 2rem;
  transform: translateX(-50%) translateY(-50%);
  border: 2px solid white;
  display: flex;
  justify-content: center;
  align-items: center;
  
}

.register{
  width: 20rem;
  height: 20rem;
  position: absolute;
  right: 0;
  top: 50%;
  border-radius: 2rem;
  transform: translateX(50%) translateY(-50%);
  border: 2px solid white;
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-form{
  transform: translateX(-10%) translateY(10%);
}
</style>